#!/usr/bin/env bash

ROOT="$( git rev-parse --show-toplevel )"
DEST="${ROOT}/tools/bin"

fetch() {
  local tool=$1; shift
  local ver=$1; shift

  local arch="$(uname -m)"
  case "$arch" in
    x86_64) arch="amd64" ;;
    aarch64) arch="arm64" ;;
    *);;
  esac
  local os="$(uname -s | awk '{ print tolower($0) }')"

  local ver_cmd=""
  local fetch_cmd=""
  case "$tool" in
    "golangci-lint")
      ver_cmd="${DEST}/golangci-lint --version 2>/dev/null | cut -d' ' -f4"
      fetch_cmd="curl -sSfL \"https://raw.githubusercontent.com/golangci/golangci-lint/v${ver}/install.sh\" | sh -s -- -b \"${DEST}\" \"v${ver}\""
      ;;
    "kind")
      ver_cmd="${DEST}/kind --version 2>/dev/null | cut -d' ' -f3"
      fetch_cmd="(curl -sSfLo '${DEST}/kind' 'https://kind.sigs.k8s.io/dl/v${ver}/kind-${os}-${arch}' && chmod +x ${DEST}/kind)"
      ;;
    "kubectl")
      ver_cmd="${DEST}/kubectl version 2>/dev/null | grep Client | cut -d' ' -f5 | sed 's/\w\+:\"v\(.*\)\",/\1/'"
      fetch_cmd="(curl -sSfLo '${DEST}/kubectl' 'https://storage.googleapis.com/kubernetes-release/release/v${ver}/bin/${os}/${arch}/kubectl' && chmod +x ${DEST}/kubectl)"
      ;;
    "envtest")
      ver_cmd="cat ${DEST}/.envtest_version 2>/dev/null"
      fetch_cmd="(test -f ${DEST}/setup-envtest.sh || curl -sSLo ${DEST}/setup-envtest.sh https://raw.githubusercontent.com/kubernetes-sigs/controller-runtime/v${ver}/hack/setup-envtest.sh) && (source ${DEST}/setup-envtest.sh; fetch_envtest_tools ${DEST}/../) && echo ${ver} > ${DEST}/.envtest_version"
      ;;
    "goreleaser")
      ver_cmd="${DEST}/goreleaser --version 2>/dev/null | grep version | cut -d' ' -f3"
      fetch_cmd="curl -sSfL https://install.goreleaser.com/github.com/goreleaser/goreleaser.sh | sh -s -- -b \"${DEST}\" -d \"v${ver}\""
      ;;
    *)
      echo "unknown tool $tool"
      return 1
      ;;
  esac

  if [[ "${ver}" != "$(eval ${ver_cmd})" ]]; then
    echo "${tool} missing or not version '${ver}', downloading..."
    mkdir -p ${DEST}
    eval ${fetch_cmd}
  fi
}

fetch $@
